<template>
  <div class="app-container">
    <div class="syl-group">
      <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.native.prevent>
        <el-form-item label="商品名称:" prop="goodsName">
          <el-input
            v-model.trim="queryParams.goodsName"
            placeholder="请输入"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" class="ordinary" style="margin-right: 20px" @click="resetQuery">
            重置
          </el-button>
          <el-button type="primary" size="mini" @click="handleAdd">新增套餐</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-radio-group v-model="queryParams.status1" @change="getStatusValue">
            <el-radio :label="3">全部菜品</el-radio>
            <el-radio :label="1">只看上架</el-radio>
            <el-radio :label="2">只看下架</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <div v-if="equWristbandList.length>0" class="syl-box">
        <el-card v-for="item in equWristbandList" :key="item.id" class="syl-card" shadow="never">
          <div class="syl-card-hennd">
            <div class="hamger">
              <img :src="serverMap.baseImg + '/'+getCuisine(item.packageImage,0)" alt="套餐图片" :onerror="defaultImg">
            </div>
            <div class="syl-frame">
              <div class="middle">
                <div class="middle-left" v-html="getNullNames(item.goodsName)" />
                <div class="middle-right" v-html="'销量:  '+ getNullNames(item.saleNum)" />
              </div>
              <div class="menu" v-html="'主菜:'+getNullNames(item.mainDishName)" />
              <div
                class="quantity"
                v-html="'配菜:'+item.firstDishName+','+item.secondDishName"
              />
              <div class="darter">
                <span class="darter-left" v-html="'￥'+ getNullNames(item.goodsPrice)" />
                <span class="darter-right">/份</span>
              </div>
            </div>
          </div>
          <div class="bottom">
            <div class="bottom-left">
              <el-button icon="el-icon-refresh" size="mini" class="ordinary" @click="handleUpdate(item)">查看
              </el-button>
            </div>
            <el-divider direction="vertical" />
            <div v-if="item.status===2" class="bottom-right">
              <el-button type="primary" size="mini" @click="getGoods(item)">商品上架</el-button>
            </div>
            <div v-if="item.status===1" class="bottom-right">
              <el-button type="primary" size="mini" @click="getGoods(item)">商品下架</el-button>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else>
        <h2>暂无数据</h2>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改门店对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1006px"
      :lock-scroll="true"
      :append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="名称" prop="goodsName">
              <el-input
                v-model.trim="form.goodsName"
                placeholder="请输入套餐名称"
                style="width: 220px"
                :maxlength="8"
              />
            </el-form-item>
            <el-form-item label="分类" prop="packageTypeId">
              <el-select v-model="form.packageTypeId" placeholder="请选择" style="width: 220px" @change="getPackage">
                <el-option
                  v-for="item in classification"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  filterable
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="金额" prop="goodsPrice">
              <el-input
                v-model.trim="form.goodsPrice"
                style="width: 220px"
                placeholder="请输入金额"
                :maxlength="3"
              />
            </el-form-item>
            <el-form-item label="主菜" prop="mainDishId">
              <el-select v-model="form.mainDishId" filterable placeholder="请选择" style="width: 220px">
                <el-option
                  v-for="item in selectedOptions"
                  :key="item.id"
                  :label="item.dishName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="sideDish" label="配菜1" prop="firstDishId">
              <el-select v-model="form.firstDishId" filterable placeholder="请选择" style="width: 220px">
                <el-option v-for="item in sideDishes1" :key="item.id" :label="item.dishName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="sideDish" label="配菜2" prop="secondDishId">
              <el-select v-model="form.secondDishId" filterable placeholder="请选择" style="width: 220px">
                <el-option v-for="item in sideDishes2" :key="item.id" :label="item.dishName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="套餐图片">
          <el-upload
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            :disabled="upload.isUploading"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
            :limit="limitCount"
            :on-success="handleAvatarSuccess"
            :on-exceed="handleAvatarData"
            :class="[hideUpload===3?'hide':'']"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="菜品简介" prop="introduction">
          <el-input
            v-model.trim="form.introduction"
            :file-list="fileList"
            type="textarea"
            :autosize="{ minRows: 5, maxRows: 10}"
            placeholder="请输入菜品描述"
            maxlength="400"
            style="width: 320px"
            show-word-limit
            resize="none"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" class="ordinary" @click="cancel">取 消</el-button>
        <el-divider direction="vertical" />
        <el-button v-preventReClick type="primary" size="small" :loading="lodaing" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--照片弹窗-->
    <el-dialog
      :title="title1"
      :visible.sync="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div style="width: 100%;text-align: center">
        <img style="width: 240px;height: 170px" :src="dialogImageUrl" alt="">
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { addGoods, getAllGoods, getById, updateStatusGoods } from '@/api/commodity/setmeal'
import serverMap from '../../../../config/serverMap'
import { listOnSale } from '@/api/commodity/variety'
import { getSetMeal } from '@/api/commodity/classification'
import userPhoto from '@/assets/image/flase.png'
// 引入image-conversion
import * as imageConversion from 'image-conversion'

export default {
  name: 'Index',
  data() {
    return {
      // 配菜
      sideDish: true,
      defaultImg: 'this.src="' + userPhoto + '"',
      limitCount: 3,
      hideUpload: null,
      dialogImageUrl: null,
      dialogVisible: false,
      // 遮罩层
      loading: false,
      lodaing: false,
      serverMap: serverMap,
      // 分类
      classification: [],
      // 主菜
      selectedOptions: [],
      // 配菜 1，2
      sideDishes1: [],
      sideDishes2: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 套餐表格数据
      equWristbandList: [],
      // 状态
      options: [],
      // 弹出层标题
      title: '',
      title1: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        // 菜品状态
        status: null,
        status1: 3
      },
      imageUrl: '',
      // 上传图片文件列表
      fileList: [],
      // 表单参数
      form: {
        goodsName: undefined,
        goodsPrice: undefined,
        firstDishName: undefined,
        introduction: undefined,
        mainDishId: undefined,
        packageImage: [],
        packageTypeId: undefined,
        secondDishId: undefined,
        status: 1
      },
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' },
          {
            pattern: /[\u4e00-\u9fa5]/,
            message: '套餐名称只能为中文',
            trigger: 'blur'
          }
        ],
        packageTypeId: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入详情', trigger: 'blur' }
        ],
        firstDishId: [
          { required: true, message: '请选择配菜1', trigger: 'blur' }
        ],
        secondDishId: [
          { required: true, message: '请选择配菜2', trigger: 'blur' }
        ],
        mainDishId: [
          { required: true, message: '请选择主菜', trigger: 'blur' }
        ],
        goodsPrice: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          {
            pattern: /^[1-9]{1}[0-9]*$/,
            message: '金额为正整数并且金额不能以0开头',
            trigger: 'blur'
          }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {
          Authorization: getToken()
        },
        // 上传的地址
        url: serverMap.base + '/api/sys/files/upload'
      }

    }
  },
  created() {
    this.getList()
    this.getSale()
    this.getSetList()
  },
  methods: {
    /** 查询套餐列表 */
    getList() {
      const { status1 } = this.queryParams
      this.queryParams.status = status1 === 3 ? null : status1
      getAllGoods(this.queryParams).then(res => {
        const { total, records } = res.data
        this.total = total
        this.equWristbandList = records
      })
    },
    /** 获取所有上架的菜品 **/
    getSale() {
      listOnSale().then(res => {
        const { data } = res
        this.selectedOptions = data.filter(item => item.dishType === 1)
        this.sideDishes1 = data.filter(item => item.dishType === 2)
        this.sideDishes2 = this.sideDishes1
      })
    },
    /** 获取分类 **/
    getSetList() {
      getSetMeal(this.queryParams).then(res => {
        this.classification = res.data
      })
    },
    /** 菜品状态 **/
    getStatusValue(value) {
      this.queryParams.status1 = value
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.sideDish = true
      this.$refs.upload.clearFiles() // 清空文件
      this.reset()
    },
    // 表单重置
    reset() {
      this.sideDish = true
      this.form = {
        goodsName: undefined,
        goodsPrice: undefined,
        firstDishName: undefined,
        introduction: undefined,
        mainDishId: undefined,
        packageImage: [],
        packageTypeId: undefined,
        secondDishId: undefined,
        status: 1
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.status1 = 3
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增套餐'
      this.$nextTick(() => {
        this.$refs.upload.clearFiles() // 清空文件
      })
    },
    /** 查看按钮操作 */
    handleUpdate(row) {
      this.fileList = []
      const arr = [null, undefined, '']
      if (row.goodsName === '盖搅饭') {
        this.sideDish = false
      }
      getById(row.id).then(res => {
        const { packageImage } = res.data
        this.form = res.data
        if (arr.includes(packageImage)) {
          this.form.packageImage = []
        } else {
          const dishImage = res.data.packageImage.split(',')
          this.form = res.data
          this.fileList = dishImage.map(item => {
            return {
              url: serverMap.baseImg + '/' + item
            }
          })
          this.hideUpload = this.fileList.length
          this.form.packageImage = dishImage
        }
        this.title = '编辑套餐'
        this.open = true
      })
    },
    /** 点击文件列表中已上传的文件时的钩子 **/
    handlePictureCardPreview(file) {
      this.title1 = '查看照片'
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 超出事件
    handleAvatarData() {
      this.msgInfo('图片上传次数最多为3张!')
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList) {
      if (res.code === 0) {
        const { data } = res
        this.form.packageImage.push(data.url)
        this.hideUpload = fileList.length >= this.limitCount
      }
    },
    /** 图片删除 */
    handleRemove(file, fileList) {
      this.form.packageImage = fileList.map((item) => item.url)
      this.hideUpload = fileList.length >= this.limitCount
    },
    /** 图片上传格式判断 */
    beforeAvatarUpload(file) {
      new Promise((resolve, reject) => {
        const isJPG = file.type.split('/')[1]
        const value = ['jpeg', 'png', 'jpg', 'bmp', 'gif', 'JPEG', 'PNG', 'JPG', 'BMP']
        const name = value.includes(isJPG)
        if (!name) {
          this.msgError('上传图片格式为' + 'jpeg', 'png', 'jpg', 'bmp', 'gif', 'JPEG', 'PNG', 'JPG', 'BMP')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        const _URL = window.URL || window.webkitURL
        // 这里需要计算出图片的长宽
        const img = new Image()
        img.onload = function() {
          file.width = img.width // 获取到width放在了file属性上
          file.height = img.height // 获取到height放在了file属性上
          const valid = img.width > 2000 // 图片宽度大于2000
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (valid || isLt2M) {
            imageConversion.compressAccurately(file, {
              size: 400,
              width: 2000
            }).then(res => { // console.log(33, res)
              resolve(res)
            })
          } else {
            resolve(file)
          }
        } // 需要把图片赋值
        img.src = _URL.createObjectURL(file)
        if (!isLt2M) {
          this.msgError('上传头像图片大小不能超过 2MB,请重新上传!')
        }
        return name && isLt2M
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      const { packageImage } = this.form
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.lodaing = true
          if (JSON.stringify(packageImage) !== '[]') {
            this.form.packageImage = packageImage.join(',')
          } else if (typeof packageImage === 'string') {
            this.form.packageImage = packageImage
          } else {
            this.msgInfo('请至少上传一张图片')
          }
          addGoods(this.form).then(res => {
            if (!res.code) {
              this.open = false
              this.lodaing = false
              this.msgSuccess('操作成功')
              this.getList()
              this.reset()
            }
          })
        }
      })
      setTimeout(() => {
        this.lodaing = false
      }, 3000)
    },
    /** 判断分类当前是否为套餐 **/
    getPackage(row) {
      let nameType = null
      nameType = this.classification.find(item => item.id === row)
      if (nameType.name === '盖浇饭') {
        this.sideDish = false
      } else {
        this.sideDish = true
      }
    },
    /** 修改商品上架或者下架 **/
    getGoods(row) {
      if (row !== undefined) {
        const data = {
          id: row.id,
          status: row.status === 1 ? 2 : 1
        }
        const text = row.status === 1 ? '下架' : '上架'
        const name = row.status === 1 ? '下架此套餐后，用户将无法看见此套餐。' : '上架此菜品后，允许添加到新的套餐内'
        this.$confirm('是否确定' + text + '该' + row.goodsName + '吗?' + '<br/>' + '<span style="color: #999999">' + name + '</span>', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          dangerouslyUseHTMLString: true,
          closeOnPressEscape: false,
          type: 'warning'
        }).then(function() {
          return updateStatusGoods(data)
        }).then(() => {
          this.msgSuccess(text + '成功')
          this.getList()
        }).catch(function() {
          return row.status
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.mb8 {
  margin-bottom: 20px;
}

.syl-col {
  margin: 0 auto;
}

.syl-box {
  width: 100%;
}

/** 卡片样式 **/
.syl-card {
  width: 290px;
  margin: 20px 10px;
  display: inline-block;

  .syl-card-hennd {
    width: 100%;
    height: auto;

    .hamger {
      width: 100%;
      height: 160px;
      text-align: center;
      border-radius: 5px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .middle {
      width: 100%;
      font-size: 16px;
      line-height: 50px;
      display: flex;
      justify-content: space-between;

      .middle-left {
        height: 50px;
        text-align: left;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }

      .middle-right {
        height: 50px;
        text-align: right;
        font-size: 14px;
        font-weight: 400;
        color: #999999;
      }
    }

    .menu {
      width: 100%;
      height: 35px;
      line-height: 35px;
      font-size: 14px;
      font-weight: 400;
      color: #666666;
    }

    .quantity {
      height: 35px;
      line-height: 35px;
      display: inline-block;
      font-size: 14px;
      font-weight: 400;
      color: #666666;
    }

    .darter {
      height: 35px;
      line-height: 35px;
      float: right;

      .darter-left {
        color: #EC1717;
        font-size: 18px;
        font-weight: 400;
      }

      .darter-right {
        font-size: 12px;
        color: #666666;
        font-weight: 400;
      }
    }
  }

  .bottom {
    width: 100%;
    height: 50px;
    border-top: 2px solid #F2F2F2;
    padding: 8px 0;
    text-align: center;
    font-size: 16px;
    display: flex;
    color: #cccccc;
    cursor: pointer;

    .bottom-left {
      width: 50%;
    }

    .bottom-right {
      width: 50%;
    }
  }
}

/deep/ .el-card__body {
  padding: 0;
}

.hide {
  /deep/ .el-upload--picture-card {
    display: none;
  }
}

.syl-frame {
  width: 100%;
  padding: 0 10px;
}

/deep/ .el-divider--vertical {
  margin: 6px 15px;
}
</style>
